// 2025/11/20: 首个版本

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RemoteConsole
{
    class ConsoleIPScan
    {
        public async Task Scan(ushort port)
        {
            if (running) return;

            running = true;
            canceling = false;
            finishedCount = 0;

            List<IPAddress> allIPs = new List<IPAddress>();
            foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (ni.NetworkInterfaceType != NetworkInterfaceType.Ethernet &&
                    ni.NetworkInterfaceType != NetworkInterfaceType.Wireless80211) continue;
                if (ni.OperationalStatus != OperationalStatus.Up) continue;

                foreach (UnicastIPAddressInformation ipInfo in ni.GetIPProperties().UnicastAddresses)
                {
                    if (ipInfo.Address.AddressFamily != AddressFamily.InterNetwork) continue;

                    var subnetMask = ipInfo.IPv4Mask;
                    if (subnetMask == null) continue;

                    var addressBytes = ipInfo.Address.GetAddressBytes();
                    var maskBytes = subnetMask.GetAddressBytes();

                    var networkBytes = new byte[4];
                    for (int i = 0; i < 4; i++) networkBytes[i] = (byte)(addressBytes[i] & maskBytes[i]);

                    var hostBits = 0;
                    for (int i = 0; i < 4; i++)
                    {
                        byte mask = maskBytes[i];
                        for (int j = 0; j < 8; j++)
                        {
                            if ((mask & (1 << (7 - j))) == 0)
                            {
                                hostBits++;
                            }
                        }
                    }
                    if (hostBits > 8) continue;

                    var hostCount = (int)Math.Pow(2, hostBits);

                    var networkValue = (uint)(networkBytes[0] << 24 | networkBytes[1] << 16 | networkBytes[2] << 8 | networkBytes[3]);
                    var maskValue = (uint)(maskBytes[0] << 24 | maskBytes[1] << 16 | maskBytes[2] << 8 | maskBytes[3]);

                    for (int i = 1; i < hostCount - 1; i++)
                    {
                        uint hostMask = ~maskValue;
                        uint hostPart = (uint)i & hostMask;
                        uint ipValue = networkValue | hostPart;

                        byte[] ipBytes = new byte[4];
                        ipBytes[0] = (byte)((ipValue >> 24) & 0xFF);
                        ipBytes[1] = (byte)((ipValue >> 16) & 0xFF);
                        ipBytes[2] = (byte)((ipValue >> 8) & 0xFF);
                        ipBytes[3] = (byte)(ipValue & 0xFF);

                        IPAddress ip = new IPAddress(ipBytes);
                        allIPs.Add(ip);
                    }
                }
            }

            var ips = allIPs.Distinct().ToArray();
            if (ips.Length == 0)
            {
                await Task.Delay(500);
                ScanProgressing?.Invoke(this, new ScanProgressingEventArgs { Progress = 100.0 });
            }
            else
            {
                var tasks = new List<Task>();
                for (int i = 0; i < ips.Length; i++)
                {
                    if (canceling) break;
                    tasks.Add(ScanOneIP(ips[i], port, ips.Length));
                    await Task.Delay(100);
                }
                await Task.WhenAll(tasks.ToArray());
            }

            running = false;
            await Task.Delay(500);
        }

        public void CancelScan()
        {
            canceling = true;
        }

        private async Task ScanOneIP(IPAddress ip, ushort port, int totalCount)
        {
            var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            try
            {
                await socket.ConnectAsync(ip, port, new CancellationTokenSource(300).Token);
            }
            catch (Exception) { }

            if (socket.Connected)
            {
                var buffer = new byte[256];
                int receivedSize = 0;
                try
                {
                    receivedSize = await socket.ReceiveAsync(buffer, new CancellationTokenSource(300).Token);
                }
                catch (Exception) { }
                if (receivedSize > 0)
                {
                    var text = Encoding.UTF8.GetString(buffer, 0, receivedSize);
                    if (text.StartsWith("This is "))
                    {
                        var machineName = text.Substring(8);
                        FoundNewIP?.Invoke(this, new FoundNewIPEventArgs { IP = ip.ToString(), MachineName = machineName });
                    }
                }

                try
                {
                    await socket.DisconnectAsync(true, new CancellationTokenSource(300).Token);
                }
                catch (Exception) { }
                socket.Close();
            }

            Interlocked.Increment(ref finishedCount);
            ScanProgressing?.Invoke(this, new ScanProgressingEventArgs { Progress = (double)finishedCount / totalCount * 100.0 });
        }

        public event ScanProgressingDelegate ScanProgressing;
        public delegate void ScanProgressingDelegate(object sender, ScanProgressingEventArgs args);

        public delegate void FoundNewIPDelegate(object sender, FoundNewIPEventArgs args);
        public event FoundNewIPDelegate FoundNewIP;

        private bool canceling = false;
        private bool running = false;
        private int finishedCount = 0;
    }

    class ScanProgressingEventArgs : EventArgs
    {
        public double Progress { get; set; } // %
    }

    class FoundNewIPEventArgs : EventArgs
    {
        public String IP { get; set; }
        public String MachineName { get; set; }
    }
}